<template>
  <div class="post-create-container">
    <!-- 顶部导航栏 -->
    <header class="header">
      <div class="header-content">
        <div class="logo-section">
          <img src="https://py-steven.com/blog/static/image/logo.png" alt="logo" class="logo" />
          <span class="site-title">发布文章</span>
          <span class="site-subtitle">blog</span>
        </div>
        <nav class="nav-menu">
          <router-link to="/home" class="nav-item">首页</router-link>
          <a href="#" class="nav-item">笔记</a>
          <div class="nav-item dropdown">
            功能 <span class="arrow">▼</span>
            <div class="dropdown-menu">
              <a href="#" class="dropdown-item">大赛练习</a>
              <a href="#" class="dropdown-item">错题下载</a>
            </div>
          </div>
          <router-link to="/post/create" class="nav-item active">发布</router-link>
          <div class="nav-item dropdown">
            关于 <span class="arrow">▼</span>
            <div class="dropdown-menu">
              <router-link v-if="authStore.isLoggedIn" to="/profile" class="dropdown-item">个人主页</router-link>
              <a href="#" class="dropdown-item" v-if="!authStore.isLoggedIn" @click.prevent="router.push('/login')">个人主页</a>
              <a href="#" class="dropdown-item">后台管理</a>
              <a href="#" class="dropdown-item" @click.prevent="handleLogout" v-if="authStore.isLoggedIn">退出账号</a>
              <router-link v-if="!authStore.isLoggedIn" to="/login" class="dropdown-item">登录</router-link>
            </div>
          </div>
        </nav>
      </div>
    </header>

    <!-- 主内容区 -->
    <main class="main-content">
      <div class="form-container">
        <form @submit.prevent="handleSubmit">
          <!-- 文章标题 -->
          <div class="form-group">
            <label class="form-label">文章标题</label>
            <input
              v-model="formData.title"
              type="text"
              class="form-input"
              placeholder="请输入文章标题"
            />
          </div>

          <!-- 文章摘要 -->
          <div class="form-group">
            <label class="form-label">文章摘要</label>
            <textarea
              v-model="formData.summary"
              class="form-textarea"
              placeholder="请输入文章摘要"
              rows="4"
            ></textarea>
          </div>

          <!-- 文章分类 -->
          <div class="form-group">
            <label class="form-label">文章分类</label>
            <div class="tag-group">
              <button
                v-for="category in categories"
                :key="category.id"
                type="button"
                class="tag-btn"
                :class="{ active: selectedCategories.includes(category.id) }"
                @click="toggleCategory(category.id)"
              >
                {{ category.name }}
              </button>
              <button type="button" class="add-tag-btn" @click="showAddTagDialog = true">
                <span class="plus-icon">+</span> 选择分类
              </button>
            </div>
          </div>

          <!-- 文章标签 -->
          <div class="form-group">
            <label class="form-label">文章标签</label>
            <div class="tag-group">
              <button
                v-for="tag in availableTags"
                :key="tag"
                type="button"
                class="tag-btn"
                :class="{ active: selectedTags.includes(tag) }"
                @click="toggleTag(tag)"
              >
                {{ tag }}
              </button>
              <button type="button" class="add-tag-btn" @click="showAddLabelDialog = true">
                <span class="plus-icon">+</span> 添加标签
              </button>
            </div>
          </div>

          <!-- 富文本编辑器工具栏 -->
          <div class="editor-toolbar">
            <button type="button" class="toolbar-btn" title="标题">H</button>
            <button type="button" class="toolbar-btn" title="粗体"><strong>B</strong></button>
            <button type="button" class="toolbar-btn" title="斜体"><em>I</em></button>
            <button type="button" class="toolbar-btn" title="删除线"><s>S</s></button>
            <span class="toolbar-divider"></span>
            <button type="button" class="toolbar-btn" title="分割线">—</button>
            <button type="button" class="toolbar-btn" title="引用">66</button>
            <span class="toolbar-divider"></span>
            <button type="button" class="toolbar-btn" title="无序列表">≡</button>
            <button type="button" class="toolbar-btn" title="有序列表">☰</button>
            <button type="button" class="toolbar-btn" title="任务列表">☑</button>
            <button type="button" class="toolbar-btn" title="减少缩进">◄</button>
            <button type="button" class="toolbar-btn" title="增加缩进">►</button>
            <span class="toolbar-divider"></span>
            <button type="button" class="toolbar-btn" title="表格">⊞</button>
            <button type="button" class="toolbar-btn" title="图片">🖼</button>
            <button type="button" class="toolbar-btn" title="链接">🔗</button>
            <button type="button" class="toolbar-btn" title="上传Markdown文件" @click="triggerFileUpload">📄</button>
            <button type="button" class="toolbar-btn" title="代码">⟨/⟩</button>
            <button type="button" class="toolbar-btn" title="代码块">CB</button>
            <span class="toolbar-divider"></span>
            <div class="scroll-toggle">
              <span class="toggle-label">Scroll</span>
              <label class="toggle-switch">
                <input v-model="syncScroll" type="checkbox" />
                <span class="toggle-slider"></span>
              </label>
            </div>
          </div>

          <!-- 文章内容编辑器 -->
          <div class="editor-container">
            <div class="editor-split">
              <!-- 左侧编辑区 -->
              <div class="editor-left">
                <div class="editor-header">Markdown 编辑</div>
                <textarea
                  v-model="formData.content"
                  class="editor-textarea"
                  placeholder="请输入文章内容，支持 Markdown 格式"
                  @scroll="handleEditorScroll"
                ></textarea>
              </div>
              <!-- 右侧预览区 -->
              <div class="editor-right">
                <div class="editor-header">实时预览</div>
                <div
                  class="preview-content"
                  v-html="renderedContent"
                  ref="previewPanel"
                ></div>
              </div>
            </div>
            <!-- 隐藏的文件上传输入 -->
            <input
              ref="fileInput"
              type="file"
              accept=".md,.markdown"
              @change="handleFileUpload"
              style="display: none;"
            />
          </div>

          <!-- 底部操作栏 -->
          <div class="footer-actions">
            <div class="word-count">共 {{ wordCount }} 字</div>
            <div class="action-buttons">
              <button type="button" class="action-btn" @click="saveDraft">
                <span class="btn-icon">📝</span>
                草稿小箱
              </button>
              <button type="button" class="action-btn" @click="manageImages">
                <span class="btn-icon">🖼</span>
                图片管理
              </button>
              <button type="button" class="action-btn" @click="saveAsTheme">
                <span class="btn-icon">🎨</span>
                保存草稿
              </button>
              <button type="submit" class="submit-btn" @click="handleSubmit" :disabled="isSubmitting">
                <span class="btn-icon">📤</span>
                {{ isSubmitting ? '发布中...' : '发布文章' }}
              </button>
            </div>
          </div>
        </form>
      </div>
    </main>

    <!-- 页脚 -->
    <footer class="footer">
      <p class="copyright">Copyright © 2025 py_Steven</p>
      <p class="icp">赣ICP备2024039848号-1</p>
    </footer>

    <!-- 添加分类对话框 -->
    <div v-if="showAddTagDialog" class="modal-overlay" @click="showAddTagDialog = false">
      <div class="modal-content" @click.stop>
        <h3>添加分类</h3>
        <input v-model="newTag" type="text" class="modal-input" placeholder="输入分类名称" />
        <div class="modal-actions">
          <button @click="addTag" class="modal-btn primary">确定</button>
          <button @click="showAddTagDialog = false" class="modal-btn">取消</button>
        </div>
      </div>
    </div>

    <!-- 添加标签对话框 -->
    <div v-if="showAddLabelDialog" class="modal-overlay" @click="showAddLabelDialog = false">
      <div class="modal-content" @click.stop>
        <h3>添加标签</h3>
        <input v-model="newLabel" type="text" class="modal-input" placeholder="输入标签名称" />
        <div class="modal-actions">
          <button @click="addLabel" class="modal-btn primary">确定</button>
          <button @click="showAddLabelDialog = false" class="modal-btn">取消</button>
        </div>
      </div>
    </div>

    <!-- 图片上传对话框 -->
    <ImageUploadDialog
      :visible="showImageUploadDialog"
      :currentImage="currentUploadingImage"
      :currentIndex="currentUploadingIndex"
      :totalImages="totalUploadingImages"
      :uploading="isUploadingImages"
      @confirm="handleImageUploadConfirm"
      @skip="handleImageUploadSkip"
      @cancel="handleImageUploadCancel"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/store/auth'
import { logout } from '@/api/auth'
import { createArticle, getCategories } from '@/api/article'
import { uploadImage } from '@/api/upload'
import message from '@/utils/message'
import { parseMarkdown } from '@/utils/markdown'
import { extractImages, batchReplaceImagePaths } from '@/utils/markdownImageProcessor'
import ImageUploadDialog from '@/components/ImageUploadDialog.vue'

// 引入 highlight.js 样式（GitHub 主题）
import 'highlight.js/styles/github.css'

const router = useRouter()
const authStore = useAuthStore()

// 表单数据
const formData = ref({
  title: '',
  summary: '',
  content: '',
  category_id: null,
  tags: '',
  cover_image: '',
  location_id: null,
  status: 1 // 默认为已发布
})

// 分类列表（从API获取）
const categories = ref([])
const selectedCategories = ref([])

// 标签列表
const availableTags = ref(['Python', 'Java', 'Vue', 'JavaScript', '前端', '后端', 'Flask', 'React'])
const selectedTags = ref([])

// 同步滚动
const syncScroll = ref(true)

// 对话框状态
const showAddTagDialog = ref(false)
const showAddLabelDialog = ref(false)
const newTag = ref('')
const newLabel = ref('')

// 加载状态
const isSubmitting = ref(false)
const isUploadingImages = ref(false)
const uploadProgress = ref({ current: 0, total: 0 })

// 图片上传对话框状态
const showImageUploadDialog = ref(false)
const currentUploadingImage = ref(null)
const currentUploadingIndex = ref(0)
const totalUploadingImages = ref(0)
const localImagesToUpload = ref([])
const imageUploadReplacements = ref([])

// 文件输入引用
const fileInput = ref(null)

// 预览面板引用
const previewPanel = ref(null)

// 计算字数
const wordCount = computed(() => {
  return formData.value.content.length
})

// 计算渲染后的 Markdown 内容
const renderedContent = computed(() => {
  return parseMarkdown(formData.value.content)
})

// 处理编辑器滚动同步
const handleEditorScroll = (event) => {
  if (syncScroll.value && previewPanel.value) {
    const scrollPercentage = event.target.scrollTop / (event.target.scrollHeight - event.target.clientHeight)
    previewPanel.value.scrollTop = scrollPercentage * (previewPanel.value.scrollHeight - previewPanel.value.clientHeight)
  }
}

// 获取分类列表
const fetchCategories = async () => {
  try {
    const response = await getCategories({ status: 1 })
    if (response.code === 200) {
      categories.value = response.data || []
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    message.error('获取分类列表失败')
  }
}

// 切换分类
const toggleCategory = (categoryId) => {
  const index = selectedCategories.value.indexOf(categoryId)
  if (index > -1) {
    selectedCategories.value.splice(index, 1)
  } else {
    selectedCategories.value = [categoryId] // 只允许选择一个分类
  }
  // 更新表单数据
  formData.value.category_id = selectedCategories.value[0] || null
}

// 切换标签
const toggleTag = (tag) => {
  const index = selectedTags.value.indexOf(tag)
  if (index > -1) {
    selectedTags.value.splice(index, 1)
  } else {
    selectedTags.value.push(tag)
  }
  // 更新表单数据
  formData.value.tags = selectedTags.value.join(',')
}

// 添加新分类（暂不支持，仅提示）
const addTag = () => {
  message.info('请联系管理员添加新分类')
  showAddTagDialog.value = false
}

// 添加新标签
const addLabel = () => {
  if (newLabel.value.trim()) {
    availableTags.value.push(newLabel.value.trim())
    selectedTags.value.push(newLabel.value.trim())
    formData.value.tags = selectedTags.value.join(',')
    newLabel.value = ''
    showAddLabelDialog.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  // 验证必填项
  if (!formData.value.title) {
    message.error('请输入文章标题')
    return
  }
  if (!formData.value.summary) {
    message.error('请输入文章摘要')
    return
  }
  if (!formData.value.content) {
    message.error('请输入文章内容')
    return
  }
  if (!formData.value.category_id) {
    message.error('请选择文章分类')
    return
  }
  if (!formData.value.tags) {
    message.error('请选择文章标签')
    return
  }

  try {
    isSubmitting.value = true
    // 将 Markdown 内容转换为 HTML
    const htmlContent = parseMarkdown(formData.value.content)

    const response = await createArticle({
      title: formData.value.title,
      content: htmlContent,  // 发送转换后的 HTML
      summary: formData.value.summary,
      category_id: formData.value.category_id,
      tags: formData.value.tags,
      cover_image: formData.value.cover_image || undefined,
      location_id: formData.value.location_id || undefined,
      status: formData.value.status
    })

    if (response.code === 200) {
      message.success('文章发布成功')
      // 跳转到首页或文章详情页
      setTimeout(() => {
        router.push('/home')
      }, 1500)
    } else {
      message.error(response.message || '文章发布失败')
    }
  } catch (error) {
    console.error('发布文章失败:', error)
    message.error(error.message || '文章发布失败')
  } finally {
    isSubmitting.value = false
  }
}

// 保存草稿
const saveDraft = async () => {
  if (!formData.value.title) {
    message.error('请至少输入文章标题')
    return
  }

  try {
    isSubmitting.value = true
    // 将 Markdown 内容转换为 HTML
    const htmlContent = formData.value.content ? parseMarkdown(formData.value.content) : '草稿内容'

    const response = await createArticle({
      title: formData.value.title,
      content: htmlContent,
      summary: formData.value.summary || '草稿摘要',
      category_id: formData.value.category_id || 1,
      tags: formData.value.tags || '草稿',
      status: 0 // 0 表示草稿
    })

    if (response.code === 200) {
      message.success('已保存到草稿箱')
    } else {
      message.error(response.message || '保存草稿失败')
    }
  } catch (error) {
    console.error('保存草稿失败:', error)
    message.error(error.message || '保存草稿失败')
  } finally {
    isSubmitting.value = false
  }
}

// 图片管理
const manageImages = () => {
  message.info('图片管理功能开发中')
}

// 保存为草稿（别名）
const saveAsTheme = () => {
  saveDraft()
}

// 触发文件上传
const triggerFileUpload = () => {
  if (fileInput.value) {
    fileInput.value.click()
  }
}

// 处理文件上传
const handleFileUpload = async (event) => {
  const file = event.target.files[0]
  if (!file) return

  // 验证文件类型
  if (!file.name.endsWith('.md') && !file.name.endsWith('.markdown')) {
    message.error('请上传 Markdown 格式的文件（.md 或 .markdown）')
    return
  }

  // 验证文件大小（限制为 5MB）
  const maxSize = 5 * 1024 * 1024
  if (file.size > maxSize) {
    message.error('文件大小不能超过 5MB')
    return
  }

  try {
    // 读取文件内容
    const reader = new FileReader()

    reader.onload = async (e) => {
      const content = e.target.result

      // 填充到编辑器
      formData.value.content = content

      // 如果标题为空，尝试从文件名提取标题
      if (!formData.value.title) {
        const fileName = file.name.replace(/\.(md|markdown)$/, '')
        formData.value.title = fileName
      }

      message.success(`文件 "${file.name}" 已成功上传`)

      // 检测是否包含本地图片
      await processMarkdownImages(content)
    }

    reader.onerror = () => {
      message.error('文件读取失败，请重试')
    }

    reader.readAsText(file, 'UTF-8')
  } catch (error) {
    console.error('文件上传失败:', error)
    message.error('文件上传失败，请重试')
  } finally {
    // 清空文件输入，允许再次上传相同文件
    if (fileInput.value) {
      fileInput.value.value = ''
    }
  }
}

// 处理 Markdown 中的图片
const processMarkdownImages = async (markdownContent) => {
  try {
    // 提取所有图片
    const images = extractImages(markdownContent)

    console.log('提取到的所有图片:', images)

    if (!images || images.length === 0) {
      return
    }

    // 过滤出本地图片
    const localImages = images.filter(img => img.isLocal)

    console.log('本地图片:', localImages)

    if (localImages.length === 0) {
      return
    }

    // 询问用户是否上传图片
    const shouldUpload = confirm(
      `检测到 ${localImages.length} 张本地图片引用，是否自动上传到服务器？\n\n` +
      `本地图片路径：\n${localImages.map(img => `- ${img.path}`).join('\n')}\n\n` +
      `点击"确定"开始上传图片。`
    )

    if (!shouldUpload) {
      message.info('已取消图片上传，请手动替换图片路径')
      return
    }

    // 初始化上传流程
    localImagesToUpload.value = localImages
    totalUploadingImages.value = localImages.length
    currentUploadingIndex.value = 0
    imageUploadReplacements.value = []

    // 显示第一张图片的上传对话框
    showNextImageUploadDialog()
  } catch (error) {
    console.error('处理图片失败:', error)
    message.error('处理图片失败')
  }
}

// 显示下一张图片的上传对话框
const showNextImageUploadDialog = () => {
  if (currentUploadingIndex.value < localImagesToUpload.value.length) {
    currentUploadingImage.value = localImagesToUpload.value[currentUploadingIndex.value]
    showImageUploadDialog.value = true
  } else {
    // 所有图片处理完成，执行路径替换
    finishImageUpload()
  }
}

// 处理对话框确认上传
const handleImageUploadConfirm = async (file) => {
  console.log('用户选择的文件:', file)

  isUploadingImages.value = true

  try {
    const imageInfo = currentUploadingImage.value
    const index = currentUploadingIndex.value

    message.info(`正在上传图片 (${index + 1}/${totalUploadingImages.value}): ${file.name}...`)

    const response = await uploadImage(file, { usage_type: 3 })

    console.log('上传响应:', response)

    if (response.code === 200 && response.data?.image?.url) {
      const newUrl = response.data.image.url
      console.log(`图片路径替换: "${imageInfo.path}" -> "${newUrl}"`)

      imageUploadReplacements.value.push({
        oldPath: imageInfo.path,
        newPath: newUrl
      })

      message.success(`图片上传成功 (${index + 1}/${totalUploadingImages.value})`)
    } else {
      console.error('上传失败，响应:', response)
      message.error(`图片上传失败: ${imageInfo.path}`)
    }
  } catch (error) {
    console.error('上传图片失败:', error)
    message.error(`上传图片失败: ${error.message}`)
  } finally {
    isUploadingImages.value = false
    // 继续下一张
    currentUploadingIndex.value++
    showImageUploadDialog.value = false
    // 延迟显示下一张，确保对话框关闭动画完成
    setTimeout(() => {
      showNextImageUploadDialog()
    }, 200)
  }
}

// 处理对话框跳过
const handleImageUploadSkip = () => {
  message.warning(`已跳过图片: ${currentUploadingImage.value.path}`)
  // 继续下一张
  currentUploadingIndex.value++
  showImageUploadDialog.value = false
  setTimeout(() => {
    showNextImageUploadDialog()
  }, 200)
}

// 处理对话框取消全部
const handleImageUploadCancel = () => {
  showImageUploadDialog.value = false
  message.info('已取消图片上传')
  // 如果有部分图片已上传，也执行替换
  if (imageUploadReplacements.value.length > 0) {
    finishImageUpload()
  }
}

// 完成图片上传，执行路径替换
const finishImageUpload = () => {
  if (imageUploadReplacements.value.length > 0) {
    console.log('开始替换路径，替换列表:', imageUploadReplacements.value)
    const oldContent = formData.value.content
    formData.value.content = batchReplaceImagePaths(formData.value.content, imageUploadReplacements.value)
    console.log('替换前内容长度:', oldContent.length)
    console.log('替换后内容长度:', formData.value.content.length)
    console.log('内容是否变化:', oldContent !== formData.value.content)
    message.success(`成功上传并替换 ${imageUploadReplacements.value.length} 张图片`)
  } else {
    message.warning('没有图片被成功上传')
  }

  // 重置状态
  localImagesToUpload.value = []
  currentUploadingImage.value = null
  currentUploadingIndex.value = 0
  totalUploadingImages.value = 0
  imageUploadReplacements.value = []
}

// 退出登录
const handleLogout = async () => {
  try {
    await logout()
    authStore.logout()
    message.success('退出登录成功')
    router.push('/login')
  } catch (error) {
    message.error(error.message || '退出登录失败')
  }
}

// 组件挂载时获取分类列表
onMounted(() => {
  fetchCategories()
})
</script>

<style scoped>
.post-create-container {
  min-height: 100vh;
  background-color: #f5f7fa;
}

/* 顶部导航栏 */
.header {
  background: white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 60px;
}

.logo-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.logo {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}

.site-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.site-subtitle {
  font-size: 14px;
  color: #999;
  background: #f0f0f0;
  padding: 2px 8px;
  border-radius: 4px;
}

.nav-menu {
  display: flex;
  gap: 30px;
  align-items: center;
}

.nav-item {
  color: #333;
  text-decoration: none;
  font-size: 14px;
  cursor: pointer;
  transition: color 0.3s;
  position: relative;
}

.nav-item:hover {
  color: #1890ff;
}

.nav-item.active {
  color: #1890ff;
  font-weight: 500;
}

.dropdown {
  position: relative;
}

.arrow {
  font-size: 10px;
  margin-left: 4px;
}

.dropdown-menu {
  position: absolute;
  top: 100%;
  right: 0;
  margin-top: 8px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 8px 0;
  min-width: 140px;
  display: none;
  opacity: 0;
  transform: translateY(-10px);
  transition: opacity 0.2s, transform 0.2s;
}

.dropdown::after {
  content: '';
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  height: 12px;
}

.dropdown:hover .dropdown-menu {
  display: block;
  opacity: 1;
  transform: translateY(0);
}

.dropdown-item {
  display: block;
  padding: 10px 20px;
  color: #333;
  text-decoration: none;
  font-size: 14px;
  transition: background 0.2s;
}

.dropdown-item:hover {
  background: #f5f5f5;
}

/* 主内容区 */
.main-content {
  max-width: 1400px;
  margin: 0 auto;
  padding: 30px 20px;
}

.form-container {
  background: white;
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.form-group {
  margin-bottom: 24px;
}

.form-label {
  display: block;
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
  font-weight: 500;
}

.form-input {
  width: 100%;
  padding: 10px 12px;
  font-size: 14px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  outline: none;
  transition: border-color 0.3s;
}

.form-input:focus {
  border-color: #1890ff;
}

.form-textarea {
  width: 100%;
  padding: 10px 12px;
  font-size: 14px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  outline: none;
  resize: vertical;
  font-family: inherit;
  transition: border-color 0.3s;
}

.form-textarea:focus {
  border-color: #1890ff;
}

/* 标签组 */
.tag-group {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.tag-btn {
  padding: 6px 16px;
  font-size: 14px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  background: white;
  color: #666;
  cursor: pointer;
  transition: all 0.3s;
}

.tag-btn:hover {
  border-color: #1890ff;
  color: #1890ff;
}

.tag-btn.active {
  background: #1890ff;
  border-color: #1890ff;
  color: white;
}

.add-tag-btn {
  padding: 6px 16px;
  font-size: 14px;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  background: white;
  color: #999;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 4px;
  transition: all 0.3s;
}

.add-tag-btn:hover {
  border-color: #1890ff;
  color: #1890ff;
}

.plus-icon {
  font-size: 16px;
  font-weight: 500;
}

/* 富文本编辑器工具栏 */
.editor-toolbar {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px;
  background: #fafafa;
  border: 1px solid #e8e8e8;
  border-bottom: none;
  border-radius: 4px 4px 0 0;
  flex-wrap: wrap;
}

.toolbar-btn {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  background: white;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  color: #666;
  transition: all 0.2s;
}

.toolbar-btn:hover {
  background: #e6f7ff;
  color: #1890ff;
}

.toolbar-divider {
  width: 1px;
  height: 20px;
  background: #e8e8e8;
}

.scroll-toggle {
  margin-left: auto;
  display: flex;
  align-items: center;
  gap: 8px;
}

.toggle-label {
  font-size: 13px;
  color: #666;
}

.toggle-switch {
  position: relative;
  display: inline-block;
  width: 42px;
  height: 22px;
}

.toggle-switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.toggle-slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  transition: 0.3s;
  border-radius: 22px;
}

.toggle-slider:before {
  position: absolute;
  content: "";
  height: 16px;
  width: 16px;
  left: 3px;
  bottom: 3px;
  background-color: white;
  transition: 0.3s;
  border-radius: 50%;
}

input:checked + .toggle-slider {
  background-color: #1890ff;
}

input:checked + .toggle-slider:before {
  transform: translateX(20px);
}

/* 编辑器 */
.editor-container {
  margin-bottom: 0;
}

.editor-split {
  display: flex;
  gap: 0;
  border: 1px solid #e8e8e8;
  border-radius: 0 0 4px 4px;
}

.editor-left,
.editor-right {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.editor-left {
  border-right: 1px solid #e8e8e8;
}

.editor-header {
  padding: 10px 16px;
  background: #fafafa;
  border-bottom: 1px solid #e8e8e8;
  font-size: 13px;
  font-weight: 500;
  color: #666;
}

.editor-textarea {
  width: 100%;
  min-height: 500px;
  padding: 16px;
  font-size: 14px;
  font-family: 'Courier New', monospace;
  border: none;
  outline: none;
  resize: vertical;
  line-height: 1.8;
  flex: 1;
}

.editor-textarea:focus {
  outline: none;
}

.preview-content {
  width: 100%;
  min-height: 500px;
  max-height: 500px;
  padding: 16px;
  font-size: 14px;
  line-height: 1.8;
  overflow-y: auto;
  background: white;
  flex: 1;
}

/* Markdown 预览样式 */
.preview-content h1 {
  font-size: 28px;
  font-weight: 600;
  margin: 20px 0 16px;
  padding-bottom: 8px;
  border-bottom: 2px solid #eaecef;
  color: #333;
}

.preview-content h2 {
  font-size: 24px;
  font-weight: 600;
  margin: 18px 0 14px;
  padding-bottom: 6px;
  border-bottom: 1px solid #eaecef;
  color: #333;
}

.preview-content h3 {
  font-size: 20px;
  font-weight: 600;
  margin: 16px 0 12px;
  color: #333;
}

.preview-content h4 {
  font-size: 18px;
  font-weight: 600;
  margin: 14px 0 10px;
  color: #333;
}

.preview-content h5 {
  font-size: 16px;
  font-weight: 600;
  margin: 12px 0 8px;
  color: #333;
}

.preview-content h6 {
  font-size: 14px;
  font-weight: 600;
  margin: 10px 0 6px;
  color: #666;
}

.preview-content p {
  margin: 12px 0;
  color: #555;
}

.preview-content code {
  background: #f6f8fa;
  padding: 2px 6px;
  border-radius: 3px;
  font-family: 'Courier New', monospace;
  font-size: 13px;
  color: #d73a49;
}

.preview-content pre {
  background: #f6f8fa;
  padding: 16px;
  border-radius: 6px;
  overflow-x: auto;
  margin: 16px 0;
}

.preview-content pre code {
  background: none;
  padding: 0;
  font-size: 13px;
  line-height: 1.6;
}

/* highlight.js 代码高亮支持 */
.preview-content pre code.hljs {
  display: block;
  padding: 0;
}

/* 表格样式 */
.preview-content table {
  border-collapse: collapse;
  width: 100%;
  margin: 16px 0;
  border: 1px solid #dfe2e5;
}

.preview-content table th,
.preview-content table td {
  border: 1px solid #dfe2e5;
  padding: 8px 12px;
  text-align: left;
}

.preview-content table th {
  background: #f6f8fa;
  font-weight: 600;
}

.preview-content strong {
  font-weight: 600;
  color: #333;
}

.preview-content em {
  font-style: italic;
}

.preview-content del {
  text-decoration: line-through;
  color: #888;
}

.preview-content a {
  color: #1890ff;
  text-decoration: none;
}

.preview-content a:hover {
  text-decoration: underline;
}

.preview-content img {
  max-width: 100%;
  height: auto;
  margin: 12px 0;
  border-radius: 4px;
}

.preview-content blockquote {
  border-left: 4px solid #dfe2e5;
  padding: 8px 16px;
  margin: 12px 0;
  background: #f6f8fa;
  color: #666;
}

.preview-content ul,
.preview-content ol {
  padding-left: 24px;
  margin: 12px 0;
}

.preview-content li {
  margin: 6px 0;
  color: #555;
}

.preview-content ul {
  list-style-type: disc;
}

.preview-content ol {
  list-style-type: decimal;
}

/* 任务列表样式 */
.preview-content li.task-list {
  list-style-type: none;
  margin-left: -20px;
}

.preview-content li.task-list.checked {
  color: #888;
  text-decoration: line-through;
}

.preview-content hr {
  border: none;
  border-top: 2px solid #eaecef;
  margin: 24px 0;
}

/* 模态框 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  padding: 24px;
  min-width: 400px;
}

.modal-content h3 {
  margin: 0 0 16px 0;
  font-size: 16px;
  color: #333;
}

.modal-input {
  width: 100%;
  padding: 10px 12px;
  font-size: 14px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  outline: none;
  margin-bottom: 16px;
}

.modal-input:focus {
  border-color: #1890ff;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.modal-btn {
  padding: 8px 20px;
  font-size: 14px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  background: white;
  color: #666;
  cursor: pointer;
  transition: all 0.3s;
}

.modal-btn:hover {
  border-color: #1890ff;
  color: #1890ff;
}

.modal-btn.primary {
  background: #1890ff;
  border-color: #1890ff;
  color: white;
}

.modal-btn.primary:hover {
  background: #40a9ff;
  border-color: #40a9ff;
}

/* 底部操作栏 */
.footer-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background: #fafafa;
  border: 1px solid #e8e8e8;
  border-top: none;
  border-radius: 0 0 4px 4px;
  margin-top: -1px;
}

.word-count {
  font-size: 14px;
  color: #999;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  font-size: 14px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  background: white;
  color: #666;
  cursor: pointer;
  transition: all 0.3s;
}

.action-btn:hover {
  border-color: #1890ff;
  color: #1890ff;
}

.submit-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 20px;
  font-size: 14px;
  border: none;
  border-radius: 4px;
  background: #52c41a;
  color: white;
  cursor: pointer;
  transition: all 0.3s;
}

.submit-btn:hover:not(:disabled) {
  background: #73d13d;
}

.submit-btn:disabled {
  background: #d9d9d9;
  cursor: not-allowed;
}

.btn-icon {
  font-size: 16px;
}

/* 页脚 */
.footer {
  background: white;
  border-top: 1px solid #e8e8e8;
  padding: 24px 20px;
  text-align: center;
  margin-top: 40px;
}

.copyright {
  font-size: 14px;
  color: #666;
  margin: 0 0 8px 0;
}

.icp {
  font-size: 13px;
  color: #999;
  margin: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .main-content {
    padding: 20px 10px;
  }

  .form-container {
    padding: 20px;
  }

  .editor-toolbar {
    gap: 4px;
    padding: 8px;
  }

  .toolbar-btn {
    width: 28px;
    height: 28px;
    font-size: 12px;
  }

  .editor-split {
    flex-direction: column;
  }

  .editor-left {
    border-right: none;
    border-bottom: 1px solid #e8e8e8;
  }

  .modal-content {
    min-width: 90%;
    margin: 0 20px;
  }

  .footer-actions {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .action-buttons {
    flex-wrap: wrap;
    justify-content: center;
  }

  .action-btn,
  .submit-btn {
    font-size: 13px;
    padding: 8px 12px;
  }
}
</style>
